import React, { useState, useEffect } from "react";
import { Card, Button, message, Popconfirm, Input, Space } from "antd";
import { DeleteOutlined, WalletOutlined } from "@ant-design/icons"; // 引入图标
import axios from "axios";
import "antd/dist/reset.css"; // 引入 Ant Design 样式

const Order = () => {
  const [orders, setOrders] = useState([]); // 存储所有订单
  const [filteredOrders, setFilteredOrders] = useState([]); // 存储过滤后的订单
  const [loading, setLoading] = useState(false); // 加载状态
  const [activeTab, setActiveTab] = useState("全部"); // 当前选中的状态（全部、待支付、已支付）
  const [searchOrderNumber, setSearchOrderNumber] = useState(""); // 存储用户输入的订单号

  // 获取订单数据
  const fetchOrders = async (orderNumber = "", tab = activeTab) => {
    setLoading(true);
    try {
      const response = await axios.get("http://localhost:5000/api/orders", {
        params: {
          status: tab, // 使用传入的 tab 参数
          order_number: orderNumber,
        },
      });
      setOrders(response.data);
      setFilteredOrders(response.data); // 后端已过滤，直接使用
    } catch (error) {
      message.error("获取订单数据失败！");
      console.error("Error fetching orders:", error);
    } finally {
      setLoading(false);
    }
  };

  // 切换状态
  const handleTabChange = (tab) => {
    setActiveTab(tab);
    fetchOrders(searchOrderNumber, tab); // 直接传递 tab 参数
  };

  // 处理订单号查询
  const handleSearch = () => {
    fetchOrders(searchOrderNumber, activeTab); // 使用当前 activeTab
  };

  // 删除订单
  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:5000/api/orders/${id}`);
      message.success("订单删除成功！");
      fetchOrders(searchOrderNumber, activeTab); // 刷新订单列表
    } catch (error) {
      message.error("删除订单失败！");
      console.error("Error deleting order:", error);
    }
  };

  // 立即支付（示例功能）
  const handlePay = (record) => {
    message.info(`支付订单 ${record.order_number}，金额 ${record.amount} 元`);
    // 支付成功后更新订单状态
    setTimeout(async () => {
      try {
        await axios.put(`http://localhost:5000/api/orders/${record.id}`, {
          status: "已支付",
        });
        message.success("支付成功！");
        fetchOrders(searchOrderNumber, activeTab); // 刷新订单列表
      } catch (error) {
        message.error("更新订单状态失败！");
        console.error("Error updating order status:", error);
      }
    }, 1000); // 模拟支付延迟
  };

  // 页面加载时获取订单数据
  useEffect(() => {
    fetchOrders();
  }, []);

  return (
    <div
      style={{
        width: "600px", // 根元素宽度 600px
        margin: "0 auto", // 居中
        padding: "20px",
        backgroundColor: "#f5f5f5",
        minHeight: "100vh",
      }}
    >
      {/* 标题和状态切换 */}
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          marginBottom: "20px",
        }}
      >
        <div>
          <span
            onClick={() => handleTabChange("全部")}
            style={{
              marginRight: "20px",
              fontSize: "24px",
              color: activeTab === "全部" ? "#ff4d4f" : "#666",
              cursor: "pointer",
              fontWeight: activeTab === "全部" ? "bold" : "normal",
            }}
          >
            全部
          </span>
          <span
            onClick={() => handleTabChange("待支付")}
            style={{
              marginRight: "20px",
              fontSize: "24px",
              color: activeTab === "待支付" ? "#ff4d4f" : "#666",
              cursor: "pointer",
              fontWeight: activeTab === "待支付" ? "bold" : "normal",
            }}
          >
            待支付
          </span>
          <span
            onClick={() => handleTabChange("已支付")}
            style={{
              fontSize: "24px",
              color: activeTab === "已支付" ? "#ff4d4f" : "#666",
              cursor: "pointer",
              fontWeight: activeTab === "已支付" ? "bold" : "normal",
            }}
          >
            已支付
          </span>
        </div>
        <Button
          type="primary"
          style={{
            backgroundColor: "#ffaa00",
            borderColor: "#ffaa00",
            borderRadius: "20px",
            fontWeight: "bold",
          }}
          onClick={() => fetchOrders(searchOrderNumber, activeTab)}
        >
          刷新
        </Button>
      </div>

      {/* 订单号查询 */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          marginBottom: "20px",
        }}
      >
        <Input
          placeholder="请输入订单号"
          value={searchOrderNumber}
          onChange={(e) => setSearchOrderNumber(e.target.value)}
          style={{
            width: "300px",
            marginRight: "10px",
            borderRadius: "5px",
          }}
        />
        <Button
          type="primary"
          style={{
            backgroundColor: "#b22222",
            borderColor: "#b22222",
            borderRadius: "5px",
            fontWeight: "bold",
          }}
          onClick={handleSearch}
        >
          查询
        </Button>
      </div>

      {/* 订单卡片列表 */}
      {loading ? (
        <div style={{ textAlign: "center", fontSize: "16px", color: "#666" }}>
          加载中...
        </div>
      ) : filteredOrders.length === 0 ? (
        <div style={{ textAlign: "center", fontSize: "16px", color: "#666" }}>
          暂无订单
        </div>
      ) : (
        filteredOrders.map((order) => (
          <Card
            key={order.id}
            style={{
              marginBottom: "20px",
              borderRadius: "10px",
              border: "2px solid #b22222", // 红色边框
              backgroundColor: "#fff", // 白色背景
            }}
            bodyStyle={{
              padding: "15px",
              display: "flex", // 使用 flex 布局
              alignItems: "center", // 垂直居中
            }}
          >
            {/* 左侧图片 */}
            <img
              src="https://img-fe.tengzhihh.com/image/568596f970f9d5-186x193.png?x-oss-process=image/format,webp"
              alt="order icon"
              style={{
                width: "186px",
                height: "193px",
                marginRight: "20px", // 图片与右侧信息的间距
              }}
            />

            {/* 右侧订单信息 */}
            <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
              <div style={{ flex: 1 }}>
                <p style={{ margin: "0", fontSize: "16px", color: "#333" }}>
                  <strong>订单号：</strong>{order.order_number}
                </p>
                <p style={{ margin: "5px 0", fontSize: "14px", color: "#666" }}>
                  <strong>姓名：</strong>{order.username}
                </p>
                <p style={{ margin: "5px 0", fontSize: "14px", color: "#666" }}>
                  <strong>下单时间：</strong>
                  {new Date(order.order_time).toLocaleString("zh-CN", {
                    timeZone: "Asia/Shanghai",
                  })}
                </p>
                <p style={{ margin: "5px 0", fontSize: "14px" }}>
                  <span style={{ color: "#ffaa00", marginRight: "10px" }}>
                    7.5折优惠
                  </span>
                  <span style={{ color: "#333" }}>已降价50元</span>
                </p>
                <p style={{ margin: "5px 0", fontSize: "14px" }}>
                  <strong>状态：</strong>
                  <span
                    style={{
                      color: order.status === "未支付" ? "#ff4d4f" : "#52c41a",
                      fontWeight: "bold",
                    }}
                  >
                    {order.status}
                  </span>
                </p>
              </div>

              {/* 操作按钮 */}
              <div
                style={{
                  display: "flex",
                  justifyContent: "flex-end",
                  gap: "10px",
                }}
              >
                <Popconfirm
                  title="确定删除此订单？"
                  onConfirm={() => handleDelete(order.id)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    type="text"
                    icon={<DeleteOutlined />}
                    style={{ color: "#999" }}
                  >
                    删除订单
                  </Button>
                </Popconfirm>
                {order.status === "未支付" && (
                  <Button
                    type="text"
                    icon={<WalletOutlined />}
                    style={{ color: "#ffaa00" }}
                    onClick={() => handlePay(order)}
                  >
                    立即支付
                  </Button>
                )}
              </div>
            </div>
          </Card>
        ))
      )}
    </div>
  );
};

export default Order;